package proj2501.lib;

import java.awt.Graphics;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JPanel;
import javax.swing.Timer;

/** JPanel for rendering animation. It automatically invoke its repaint method in
 * given interval. Implements timing control using javax.swing.Timer object.*/
public class RefreshingPanel extends JPanel {
	private RefreshingTimer timer;
	public RefreshingPanel() {
		timer = new RefreshingTimer();
		setDelayFromFps();
		setInitialDelayFromFps();
		
//		setFpsTarget(60);
//		setIntervalMillis(1000);
	}
	
	private static double FPS_TARGET_DEFAULT = 30;
	private double fpsTarget = FPS_TARGET_DEFAULT;
	/** Gets aimed FPS (frames per second) number. */
	public double getFpsTarget() { return fpsTarget; }
	/** Sets aimed FPS (frames per second) number. */
	public void setFpsTarget(double fps) {
		fpsTarget = fps;
		setDelayFromFps();
	}
	private void setDelayFromFps() {
		timer.setDelay((int)(1000 / fpsTarget));
	}
	private void setInitialDelayFromFps() {
		timer.setInitialDelay((int)(1000 / fpsTarget));
	}
	/** Sets interval time in milliseconds. */
	public void setIntervalMillis(int millis) {
		timer.setDelay(millis);
	}
	private int frameCount;
	/** Gets a count number of rendering frames; begins from 1. */
	public int getFrameCount() { return frameCount; }
	
	private boolean isStopped;
	/** Stops automatic refreshing. */
	public void stopRefreshing() {
		timer.stop();
		isStopped = true;
	}
	/** Starts automatic refreshing. */
	public void startRefreshing() {
		isStopped = false;
		timer.setInitialDelay(0);
		timer.start();
	}
	private boolean firstTimePaintingDone;
	@Override
	protected void paintComponent(Graphics g) {
		frameCount++;
		if (!firstTimePaintingDone && !isStopped) {
			timer.start();
			firstTimePaintingDone = true;
		}
		
		super.paintComponent(g);
	}
	private class RefreshingTimer extends Timer {
		public RefreshingTimer() {
			super(0, new TimerAction());
		}
//		@Override
//		public void start() {
//			super.start();
//			System.out.println("Executing RefreshingTimer - start method.");
//		}
	}
	private class TimerAction extends AbstractAction {
		@Override
		public void actionPerformed(ActionEvent e) {
			repaint();
		}
	}
}
